package simulator;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * Provides telemetry data for client applications(such as the dashboard)
 * via a serversocket, also simulating the telemetry daemon in the 
 * CreatePlatform
 * @author anand
 *
 */
public class SnitchActor extends Thread  implements Actor{
	public static final int PORT = 8080;

	String message;
	boolean newData;
	boolean running;
	PrintWriter out;
	ServerSocket server;
	Socket client;

	public SnitchActor(){
		message = "";
		newData = false;
		try {
			server = new ServerSocket(PORT);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void act(Robot s) {}

	public String getMaze() {
		return "";
	}

	public void run(){
		running = true;
		//init ServerSocket
		//Wait for connection
		try {
			client = server.accept();
			out = new PrintWriter(client.getOutputStream());
		} catch (IOException e1) {
			e1.printStackTrace();
			running = false;
		}

		while(running){
			//Write data
			//System.out.println(message);
			if(newData){
				out.write(message+"\n");
				out.flush();
				newData = false;
			}else
				try{this.sleep(50);}catch(Exception e){};
		}
	}

	public void updateSensors(Sensor[] sensors) {
		message = "";
		for (int i = 0; i < sensors.length; i++) {
			message += sensors[i].getID() + " ";
			for (int j = 0; j < sensors[i].getState().length-1; j++) {
				message += sensors[i].getState()[j];
				message+=";";
			}
			message+="1.0";
			if(i<sensors.length-1)
				message += "\t";
		}
		newData = true;
	}

}
